import React, { useState, useRef, useEffect } from 'react'
import s from './style.module.css'
import i from '@/index.module.css';
import cn from 'classnames'
import {
  Button,
  Icon,
  Switch,
  Input,
  Message,
  Radio,
  Dialog,
  Table,
  Confirm,
  Tooltip,
  Loading,
  Form
} from '@knownsec/react-component';

import BreadCrumb from '@/components/BreadCrumb';

import { SnmpConfigModify } from '~/API';
import nodata1 from '@/assets/svg/nodata1.svg';
// import { getErrorMessage } from '@/common/constant';


export default function SnmpConfig () {
  const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 20 },
  };
  const [visible, setVisible] = useState(false)
  const [loading, setLoading] = useState(false)
  const [protocol, setProtocol] = useState('MD5')
  const [secretkey, setSecretkey] = useState('DES')
  const [level, setLevel] = useState('noauth')
  const [switchVal, setSwitchVal] = useState(0)
  const [comunity, setComunity] = useState('')
  const [data, setData] = useState([])
  const form = useRef()
  const changeItem = (t, val) => {
    form.current.setFieldsValue({ [t]: val })
  }
  useEffect(() => {
    getConfigs()
  }, [])
  const getConfigs = () => {
    SnmpConfigModify('GET').then(res => {
      setSwitchVal(res.data?.service_status || 0)
      setComunity(res.data.group_name)
      const data = res.data.user_list.map((item, index) => {
        return {index, ...item}
      })
      setData(data)
    })
  }
  const getErrorMessage = (err) => {
    return Object.values(err)[0] || '未知错误'
  }
  const modifySwitch = (value, type) => {
    let data
    if (type === 'switch') {
      data = { action: value ? 'on' : 'off' }
    } else if (type === 'comunity') {
      data = { action: 'set', group_name: value }
    } else if (type === 'delete') {
      data = { action: 'delete', user_info: { username: value } }
    }
    setLoading(true)
    SnmpConfigModify('POST', data).then(res => {
      setLoading(false)
      Message.show({
        pro: true,
        type: res.status === 'success' ? 'success' : 'error',
        message: res.data.detail || Object.values(res.message)[0],
        showClose: false,
      })
      getConfigs()
    }).catch(err => {
      setLoading(false)
      Message.show({ type: 'error',showClose: false, message: getErrorMessage(err.data) })
    } )
  }
  const deleteItem = (user) => {
    Confirm({
      title: '提示',
      pro: true,
      message: (<div className={cn(i.tac, i.mb10)}>你确定要删除该配置吗？</div>),
      onconfirm: () => {
        modifySwitch(user, 'delete')
      }
    })
  }
  // const editItem = (item) => {
  //   let slevel = ''
  //   if (item.safe_level === '认证不加密') {
  //     slevel = 'auth'
  //   } else if (item.safe_level === '认证且加密') {
  //     slevel = 'priv'
  //   } else if (item.safe_level === '不认证不加密') {
  //     slevel = 'noauth'
  //   }
  //   setLevel(slevel)
  //   setProtocol(item.auth_agreement)
  //   setSecretkey(item.encr_agreement)
  //   form.current.setFieldsValue(item)
  //   setVisible(true)
  // }
  const btnSubmit = () => {
    setLoading(true);
    form.current.validateFields().then(res => {
      const obj = Object.assign({}, res)
      obj.safe_level = level
      obj.auth_agreement = protocol
      obj.encr_agreement = secretkey
      setLoading(true)
      SnmpConfigModify('POST', { action: 'add', user_info: obj }).then(res => {
        setLoading(false)
        Message.show({
          pro: true,
          type: res.status === 'success' ? 'success' : 'error',
          message: res.data.detail || Object.values(res.message)[0],
          onclose () {
            if (res.status === 'success') {
              setVisible(false)
              getConfigs()
            }
          }
        })
      }).catch(err => {setLoading(false); Message.show({ type: 'error',showClose: false, message: getErrorMessage(err.data) })})
    })
  }
  const agreement=(item)=>{
      if(!item.auth_agreement && !item.encr_agreement){
          return '--'
      }else{
        return `${item.auth_agreement}${(!item.auth_agreement || !item.encr_agreement )? '' : '/'}${item.encr_agreement}`
      }
  }
  const column = [
    { title: '编号', key: 'index', dataIndex: 'index' },
    { title: '用户名 (安全名)', key: 'username', dataIndex: 'username' ,render:(e)=>{return e||'--'}},
    { title: '认证/加密协议', render: (cur, item) => {
      return (
      <span>{agreement(item)}</span>
      )
    } },
    { title: '安全等级', key: 'safe_level', dataIndex: 'safe_level' ,render:(e)=>{return e||'--'}},
    { title: '操作', key: 'make', render: (cur, item) => {
      return (
        <>
          <span className={cn(i.mainColor, i.cp)} onClick={() => deleteItem(item.username)}>删除</span>
        </>
      )
    }}
  ]
  return (
    <div className={i.mainContent}>
      <BreadCrumb
        arr={[
          { link: '', name: '网络配置' },
          { link: '', name: 'SNMP配置', active: true },
        ]}
      />
      <div className={cn(s.content, i.p24, i.oa, i.h100p, i.mins)}>
        <div className={s.bgc}>
          <div className={i.p24}>
            <p>v1/v2c</p>
            <div className={cn(i.df, i.aic, i.mt24)}>
              <span className={i.primaryColor}>启用Snmp</span>
              {/* <Loading show={loading} /> */}
              <Switch
                pro
                onChange={(bool) => {
                  setSwitchVal(Number(bool));
                  modifySwitch(Number(bool), 'switch');
                }}
                className={s.ml56}
                checked={switchVal}
              />
            </div>
            <div className={cn(i.df, i.aic, i.mt24)}>
              <span className={i.primaryColor}>Community</span>
              <Input
                pro
                className={cn(s.ml46, i.dib, s.w170)}
                value={comunity}
                onChange={({ value }) => setComunity(value)}
              />
            </div>
            <div className={i.mt24}>
              <Button
                type="primary"
                onClick={() => {
                  modifySwitch(comunity, 'comunity');
                }}
              >
                确认
              </Button>
            </div>
            <div className={s.mt40}>
              <div className={cn(i.df, i.aic, i.jcsb)}>
                <p>v3</p>
                <Button
                  type="primary"
                  size="small"
                  onClick={() => {
                    setLevel('');
                    setProtocol('');
                    setSecretkey('');
                    form.current.resetFields();
                    setVisible(true);
                  }}
                >
                  <Icon type="add" className={i.vam} />
                  <span className={cn(i.vam, i.ml5)}>新建</span>
                </Button>
              </div>
              <div className={i.mt20}>
                <Table
                  columns={column}
                  data={data}
                  tableLoading={loading}
                  loadingLabel=""
                  empty={
                    <div className={cn(i.p20, i.w100p, i.blackLineColor, i.fs14, i.tac)}>
                      <img src={nodata1} alt="" />
                    </div>
                  }
                />
              </div>
            </div>
          </div>
        </div>
      </div>
      {/* 添加 */}
      <Dialog
        title="添加"
        visible={visible}
        cancelText=""
        confirmText=""
        className={s.w540}
        onhide={() => {
          form.current.resetFields();
          setVisible(false);
        }}
      >
        <div className={cn(i.p24, i.tal)}>
          <Form ref={form} {...layout}>
            <div>
              <Form.Item
                name="username"
                label="用户名"
                rules={[{ required: true, message: '用户名不能为空' }]}
              >
                <Form.Item name="username" noStyle>
                  <Input
                    pro
                    className={cn(i.dib, i.w300)}
                    onChange={({ value }) => changeItem('username', value)}
                  />
                </Form.Item>
                <Tooltip placement="right" overlay={'请使用字母和数字，不要用中文，20个字符以内'}>
                  <Icon type="question" className={cn(s.qust, i.cp)} />
                </Tooltip>
              </Form.Item>
              <div className={cn(i.df, i.aic)}>
                <p className={cn(i.w100, i.mr10)}>认证协议</p>
                <Radio.Group onChange={(e) => setProtocol(e.target.value)} value={protocol}>
                  <Radio value={'MD5'}>MD5</Radio>
                  <Radio value={'SHA'}>SHA</Radio>
                </Radio.Group>
              </div>
            </div>
            <div className={cn(i.mt24, i.pr)}>
              <Form.Item
                name="password"
                label="认证用Key"
                rules={[{ required: true, message: '认证用Key不能为空' }]}
              >
                <Form.Item name="password" noStyle>
                  <Input
                    pro
                    className={cn(i.dib, i.w300)}
                    onChange={({ value }) => changeItem('password', value)}
                  />
                </Form.Item>
                <Tooltip placement="right" overlay="请用字母，数字，下划线表示，8到100个字符之间">
                  <Icon type="question" className={cn(s.qust, i.cp)} />
                </Tooltip>
              </Form.Item>
              <div className={cn(i.df, i.aic)}>
                <p className={cn(i.w100, i.mr10)}>加密协议</p>
                <Radio.Group onChange={(e) => setSecretkey(e.target.value)} value={secretkey}>
                  <Radio value={'DES'}>DES</Radio>
                  <Radio value={'AES'}>AES</Radio>
                </Radio.Group>
              </div>
            </div>
            <div className={i.mt24}>
              <Form.Item
                name="encryption"
                label="加密用Key"
                rules={[{ required: true, message: '加密用Key不能为空' }]}
              >
                <Form.Item name="encryption" noStyle>
                  <Input
                    pro
                    className={cn(i.dib, i.w300)}
                    onChange={({ value }) => changeItem('encryption', value)}
                  />
                </Form.Item>
                <Tooltip placement="right" overlay="请用字母，数字，下划线表示，8到100个字符之间">
                  <Icon type="question" className={cn(s.qust, i.cp)} />
                </Tooltip>
              </Form.Item>
              <div className={cn(i.df, i.aic)}>
                <p className={cn(i.w100, i.mr10)}>安全等级</p>
                <Radio.Group onChange={(e) => setLevel(e.target.value)} value={level}>
                  <Radio value={'noauth'}>不认证</Radio>
                  <Radio value={'auth'}>需认证</Radio>
                  <Radio value={'priv'}>认证且加密</Radio>
                </Radio.Group>
              </div>
            </div>
          </Form>
        </div>
        <div className={cn(i.tac)} style={{marginBottom: 20}}>
          <Button onClick={() => setVisible(false)} size="small">
            取消
          </Button>
          <Button
            type="primary"
            className={cn(i.ml24, i.vat)}
            size="small"
            onClick={() => btnSubmit()}
          >
            保存
          </Button>
        </div>
      </Dialog>
    </div>
  );
}
